<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 提示条 -->
      <el-alert title="添加商品信息" type="info" center show-icon :closable="false"></el-alert>
      <!-- 步骤条 -->
      <el-steps :space="200" :active="activeStep - 0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- 侧边栏 -->
      <el-form :model="addGoodsForm" :rules="addGoodsRules" ref="addGoodsFormRef" label-width="100px" label-position="top">
        <el-tabs :tab-position="'left'" v-model="activeStep" :before-leave="beforeTabLeave" @tab-click="tabClicked">
          <!-- 基本信息 面板 -->
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addGoodsForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addGoodsForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addGoodsForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addGoodsForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader v-model="addGoodsForm.goods_cat" :options="goodsCate" :props="propsCate" @change="handleCateChange" clearable></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <!-- 商品参数 面板 -->
          <el-tab-pane label="商品参数" name="1">
            <el-form-item :label="item.attr_name" v-for="item in manyParams" :key="item.attr_id">
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox v-for="(item1, index1) in item.attr_vals" :key="index1" :label="item1" border></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <!-- 商品属性 面板 -->
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.attr_name" v-for="item in onlyParams" :key="item.attr_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <!-- 商品图片 面板 -->
          <el-tab-pane label="商品图片" name="3">
            <!-- 1、action:图片要上传到的后台API地址 -->
            <!-- 2、on-preview:点击文件列表中已上传的文件时的钩子 -->
            <!-- 3、on-remove:文件列表移除文件时的钩子 -->
            <!-- 4、file-list:上传的文件列表, 例如: [{name: 'food.jpg', url: 'https://xxx.cdn.com/xxx.jpg'}] -->
            <!-- 5、list-type:文件列表的类型(text/picture/picture-card) -->
            <el-upload
              action="http://127.0.0.1:8888/api/private/v1/upload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
              list-type="picture"
              :headers="headersObj">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <!-- 商品内容 面板 -->
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addGoodsForm.goods_introduce"></quill-editor>
            <el-button type="primary" class="btnAdd" @click="addGoods">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 预览图片对话框 -->
    <el-dialog
      title="图片预览"
      :visible.sync="previewDialogVisible"
      width="50%">
      <img :src="previewImg" alt="图片丢失" class="previewImg">
    </el-dialog>
  </div>
</template>

<script>
import _ from 'lodash'
export default {
  data() {
    return {
      activeStep: '0',
      // 添加表单的数据对象
      addGoodsForm: {
        goods_name: '',
        goods_price: 0,
        goods_number: 0,
        goods_weight: 0,
        goods_cat: [],
        pics: [],
        goods_introduce: '',
        attrs: []
      },
      // 添加表单的验证规则
      addGoodsRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_cat: [
          { required: true, message: '请选择商品分类', trigger: 'blur' }
        ]
      },
      // 商品分类对象
      goodsCate: [],
      propsCate: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 动态参数列表
      manyParams: [],
      // 静态参数列表
      onlyParams: [],
      // 图片上传请求头
      headersObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      // 预览放大图片地址
      previewImg: '',
      // 预览图片对话框显隐
      previewDialogVisible: false
    }
  },
  created() {
    this.getGoodsCateList()
  },
  computed: {
    cateId() {
      if(this.addGoodsForm.goods_cat.length === 3) {
        return this.addGoodsForm.goods_cat[2]
      }
      return null
    }
  },
  methods: {
    // 获取商品分类列表
    async getGoodsCateList() {
      const { data: res } = await this.$http.get('categories')
      if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
      // console.log(res.data)
      this.goodsCate = res.data
    },
    // 选择商品分类改变
    handleCateChange() {
      // console.log(this.addGoodsForm.goods_cat)
      if(this.addGoodsForm.goods_cat.length !== 3) {
        this.addGoodsForm.goods_cat = []
      }
    },
    // 标签页切换时触发的函数
    beforeTabLeave(activeName, oldActiveName) {
      if(oldActiveName === '0' && this.addGoodsForm.goods_cat.length !== 3) {
        this.$message.error('请先选择商品分类！')
        return false
      }
    },
    // 获取动态参数信息
    async getManyParams() {
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: 'many' } })
      if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
      // console.log(res.data)
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals.length === 0 ? [] : item.attr_vals.split(',')
      })
      this.manyParams = res.data
    },
    // 获取静态属性
    async getOnlyParams() {
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: 'only' } })
      if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
      console.log(res.data)
      this.onlyParams = res.data
    },
    // 点击已上传文件,预览图片
    handlePreview(file) {
      this.previewImg = file.response.data.url
      this.previewDialogVisible = true
    },
    // 文件列表移除时
    handleRemove(file) {
      const filePath = file.response.data.tmp_path
      // 当数组中的元素在测试条件时返回 true 时, findIndex() 返回符合条件的元素的索引位置，之后的值不会再调用执行函数;如果没有符合条件的元素返回 -1
      const idx = this.addGoodsForm.pics.findIndex(x => x.pic === filePath)
      this.addGoodsForm.pics.splice(idx, 1)
    },
    // 文件上传成功时
    handleSuccess(response) {
      const picInfo = { pic: response.data.tmp_path }
      this.addGoodsForm.pics.push(picInfo)
    },
    // 切换tabs标签项
    tabClicked() {
      if(this.activeStep === '1') {
        this.getManyParams()
      } else if(this.activeStep === '2') {
        this.getOnlyParams()
      }
    },
    // 添加商品
    addGoods() {
      this.$refs.addGoodsFormRef.validate(async valid => {
        if(!valid) return this.$message.error('请填写必要的表单项！')
        // lodash插件 cloneDeep(obj)深拷贝，先把addGoodsForm 深拷贝一份，不影响原来的，因为级联选择器要求双向绑定的是数组，所以不能直接转换为字符串，会报错
        const form = _.cloneDeep(this.addGoodsForm)
        form.goods_cat = form.goods_cat.join(',')
        this.manyParams.forEach(item => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(',')
          }
          this.addGoodsForm.attrs.push(newInfo)
        })
        this.onlyParams.forEach(item => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          }
          this.addGoodsForm.attrs.push(newInfo)
        })
        form.attrs = this.addGoodsForm.attrs
        const { data: res } = await this.$http.post('goods', form)
        if(res.meta.status !== 201) return this.$message.error('创建商品失败！')
        this.$message.success('创建商品成功！')
        this.$router.push('/goods')
      })
    }
  }
}
</script>

<style lang="less" scoped>
.el-steps{
  justify-content: center;
}
.el-checkbox{
  margin: 0 10px 0 0!important;
}
.previewImg{
  width: 100%;
}
.btnAdd{
  margin-top: 15px;
}
</style>
